package com.wenjie.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author wwj
 * @date 2021/2/3 0003 16:26
 */
@EnableWebSecurity
public class securityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 设置权限对应的开放路径
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页可以有人访问但是功能业有权限的人才能够访问  vip1只能访问level1下的页面
        http.authorizeRequests().antMatchers("/js/**","/css/**/","/images/*","/static/qinjiang/**","/**/*.png","/**/*.jpg").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");


        //没有权限默认到登录页
        http.formLogin();

    }

    /**
     * 此处是认证，springboot2.1.x 可以直接使用
     * 其他版本会报错，报错描述是需要密码编码，也就是说密码需要加密PasswordEncoder
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //平时都是从数据库中取
        auth
                .inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1")
                .and().withUser("user").password(new BCryptPasswordEncoder().encode("admin")).roles("vip2")
                .and().withUser("tset").password(new BCryptPasswordEncoder().encode("admin")).roles("vip3")
                .and().withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1","vip2","vip3");
      //数据库取出样式
//        auth
//                .jdbcAuthentication().dataSource(new BCryptPasswordEncoder(dataSource))
//                .withDefaultSchema()
//                .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1")
//                .and().withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vips");

    }
}
